<template>
  <div class="default-main ba-table-box">
    <div class="block">
      <div class="table-block">
        <el-alert class="ba-table-alert"
                  v-if="baTable.table.remark"
                  :title="baTable.table.remark"
                  type="info"
                  show-icon />
        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                     :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
          <template #shop>
            <el-select filterable
                       v-model="baTable.comSearch.form['shop_id']"
                       clearable>
              <el-option v-for="item in shop_arr"
                         :key="item.shop_id"
                         :label="item.shop_name"
                         :value="item.shop_id">
              </el-option>
            </el-select>
          </template>
          <template #month>
            <el-date-picker v-model="baTable.comSearch.form['date']"
                            type="month"
                            placeholder="选择月份"
                            value-format="YYYY-MM" />
          </template>
        </TableHeader>

        <el-row style="margin: 10px 0;"
                :gutter="10">
          <el-col :span="1.5"
                  v-if="baTable.auth('export')">
            <el-button type="warning"
                       @click="exportExcelOperate"
                       :loading="state.buttonLoading">
              <Icon :color="'#ffffff'"
                    name="el-icon-Position" />导出
            </el-button>
          </el-col>
        </el-row>
        <Table show-summary
               :summary-method="getSummaries"></Table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, provide, onBeforeMount } from 'vue'
import { ElMessageBox } from 'element-plus'
import baTableClass from '/@/utils/baTable'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi, fileDownload } from '/@/api/common'
import { useAdminInfo } from '/@/stores/adminInfo'
import Cookies from 'js-cookie'
import { useI18n } from 'vue-i18n'
import { concat } from 'lodash-es'
import { exportExcel, exportExcelInfo } from '/@/api/backend/checkbill/storeReport'
import { getShopList } from '/@/api/backend/common'

defineOptions({
    name: 'checkbill/storeReport',
})
const { t } = useI18n()
const state: {
    buttonLoading: boolean
} = reactive({
    buttonLoading: false
})
const adminInfo = useAdminInfo()
const shop_arr = ref([] as any[])

let optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: '导出',
        title: '',
        text: '导出',
        type: 'warning',
        icon: '',
        class: 'table-row-info',
        disabledTip: false,
        display: (row: TableRow, field: TableColumn) => {
            return baTable.auth('export')
        },
        click: (row: TableRow) => {
            infoExportExcel(row)
        }
    }
]
optButtons = concat(defaultOptButtons(['edit', 'delete']), optButtons)
optButtons[1].display = (row) => {
    return row.id != adminInfo.id
}

const baTable = new baTableClass(
    new baTableApi('/checkbill/storeReport/'),
    {
        column: [
            {   
                label: '月份', 
                prop: 'date', 
                align: 'center',
                operator: false
            },
            {
                label: '店铺',
                prop:  'shop_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'shop',
                show: false
            },
            {   
                label: '店铺', 
                prop: 'shop_name', 
                align: 'center',
                operator: false
            },
            {
                label: '月份',
                prop:  'date',
                operator: '=', 
                comSearchRender:'slot',
                comSearchSlotName: 'month',
                show: false
            },
            {   label: '销售收入', 
                prop: 'PanelSalesRevenue', 
                align: 'center',
                operator: false
            },
            {   label: '退款总额', 
                prop: 'refund_subtotal', 
                align: 'center',
                operator: false
            },
            {   label: '平台结算费', 
                prop: 'PlatformSettlementFee', 
                align: 'center',
                operator: false
            },
            {   label: '刷单金额', 
                prop: 'BrushSale', 
                align: 'center',
                operator: false
            },
            {   label: '销售收入净值', 
                prop: 'NetSalesRevenue', 
                align: 'center',
                operator: false
            },
            {   label: '采购成本', 
                prop: 'ProcurementCostTotal', 
                align: 'center',
                operator: false
            },
            {   label: '头程分摊', 
                prop: 'first_fees', 
                align: 'center',
                operator: false
            },
            {   label: '海外仓运费', 
                prop: 'storage_fees', 
                align: 'center',
                operator: false
            },
            {   label: '广告费账单', 
                prop: 'advertising_spend', 
                align: 'center',
                operator: false
            },
            {   label: '广告费预估返点(10%)', 
                prop: 'AdvEstimatedRebate', 
                align: 'center',
                operator: false
            },
            {   label: '广告净花费', 
                prop: 'AdvNetExpenses', 
                align: 'center',
                operator: false
            },
            {   label: '利润净值', 
                prop: 'monthProfit', 
                align: 'center',
                operator: false
            },
            // {   label: '账面订单量', 
            //     prop: 'count', 
            //     align: 'center',
            //     operator: false
            // },
            // {   label: '刷单量', 
            //     prop: 'BrushCount', 
            //     align: 'center',
            //     operator: false
            // },
            // {   label: '实际订单量', 
            //     prop: 'ActualOrderQuantity', 
            //     align: 'center',
            //     operator: false
            // },
            // {   label: '每单平均价', 
            //     prop: 'AveragePricePerOrder', 
            //     align: 'center',
            //     operator: false
            // },
            // {   label: '订单量占比', 
            //     prop: 'd22', 
            //     align: 'center',
            //     operator: false
            // },
            {
                label: t('Operate'),
                align: 'center',
                width: '100',
                render: 'buttons',
                buttons: optButtons,
                operator: false
            }
        ],
        dblClickNotEditColumn: ['all']
    }
)

provide('baTable', baTable)
baTable.table.filter!.limit = 20
baTable.mount()
baTable.getIndex()

const getSummaries = (param:any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column:any, index:any) => {
    const key = column.columnKey
    switch(key){
        case 'date':
            sums[index] = `总计: ${String(baTable.table.total)}条`
            break
        case 'PanelSalesRevenue':
            sums[index] = `${baTable.table.extend?.PanelSalesRevenue_total}`
            break
        case 'refund_subtotal':
            sums[index] = `${baTable.table.extend?.refund_subtotal_total}`
            break
        case 'PlatformSettlementFee':
            sums[index] = `${baTable.table.extend?.PlatformSettlementFee_total}`
            break
        case 'BrushSale':
            sums[index] = `${baTable.table.extend?.BrushSale_total}`
            break
        case 'NetSalesRevenue':
            sums[index] = `${baTable.table.extend?.NetSalesRevenue_total}`
            break
        case 'ProcurementCostTotal':
            sums[index] = `${baTable.table.extend?.ProcurementCostTotal_total}`
            break
        case 'first_fees':
            sums[index] = `${baTable.table.extend?.first_fees_total}`
            break
        case 'storage_fees':
            sums[index] = `${baTable.table.extend?.storage_fees_total}`
            break
        case 'advertising_spend':
            sums[index] = `${baTable.table.extend?.advertising_spend_total}`
            break
        case 'AdvEstimatedRebate':
            sums[index] = `${baTable.table.extend?.AdvEstimatedRebate_total}`
            break
        case 'AdvNetExpenses':
            sums[index] = `${baTable.table.extend?.AdvNetExpenses_total}`
            break
        case 'monthProfit':
            sums[index] = `${baTable.table.extend?.monthProfit_total}`
            break
        default:
            sums[index] = ''
    }
  })
  return sums
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
        state.buttonLoading = false
        baTable.table.loading = false
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}
const infoExportExcel = (row:TableRow) => {
    baTable.table.loading = true
    exportExcelInfo('post', {id: row.id}).then(response => {
        fileDownload(response, Cookies.get('filename') || 'file.xlsx')
    }).finally(() => { 
        baTable.table.loading = false
    })
}

const getShopArr = () => {
    getShopList().then(res => {
        if(res.data && res.data.list.length) {
            shop_arr.value = res.data.list
        }
    })
}

onBeforeMount(async () => {
    getShopArr()
})

</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-input){
    width: var(--el-input-width);
}
:deep(.el-table__header .cell){
    white-space: normal !important;
}
</style>
